import {
  Controller,
  Get,
  Post,
  Put,
  Delete,
  Body,
  Param,
  Query,
  UseGuards,
} from "@nestjs/common";
import { AnnouncementService } from "../services/announcement.service";
import { AuthGuard } from "../auth/auth.guard";

@Controller("announcement")
export class AnnouncementController {
  constructor(private readonly announcementService: AnnouncementService) {}

  /**
   * 获取公告列表（分页）
   * GET /announcement/list?pageNum=0&pageSize=20
   */
  @Get("list")
  async getAnnouncementList(
    @Query("pageNum") pageNum?: number,
    @Query("pageSize") pageSize?: number
  ) {
    try {
      const result = await this.announcementService.getAnnouncementList(
        pageNum || 0,
        pageSize || 20
      );
      return {
        act_id: 90,
        code: 0,
        list: result.list,
        total: result.total,
        pageNum: result.pageNum,
        pageSize: result.pageSize,
        totalPages: result.totalPages,
      };
    } catch (error: any) {
      return {
        act_id: 90,
        code: -1,
        msg: error?.message || "获取公告列表失败",
        list: [],
      };
    }
  }

  /**
   * 获取公告详情
   * GET /announcement/:id
   */
  @Get(":id")
  async getAnnouncementById(@Param("id") id: number) {
    try {
      const announcement = await this.announcementService.getAnnouncementById(id);
      return {
        act_id: 91,
        code: 0,
        data: announcement,
      };
    } catch (error: any) {
      return {
        act_id: 91,
        code: -1,
        msg: error?.message || "获取公告详情失败",
      };
    }
  }

  /**
   * 创建新公告
   * POST /announcement/create
   */
  @Post("create")
  @UseGuards(AuthGuard)
  async createAnnouncement(
    @Body()
    announcementData: {
      title: string;
      content: string;
      state?: number;
      priority?: number;
      publisher?: string;
      publishTime?: Date;
    }
  ) {
    try {
      const announcement = await this.announcementService.createAnnouncement(
        announcementData
      );
      return {
        act_id: 92,
        code: 0,
        data: announcement,
        msg: "公告创建成功",
      };
    } catch (error: any) {
      return {
        act_id: 92,
        code: -1,
        msg: error?.message || "创建公告失败",
      };
    }
  }

  /**
   * 更新公告
   * PUT /announcement/:id
   */
  @Put(":id")
  @UseGuards(AuthGuard)
  async updateAnnouncement(
    @Param("id") id: number,
    @Body()
    updateData: Partial<{
      title: string;
      content: string;
      state: number;
      priority: number;
      publisher: string;
      publishTime: Date;
      offlineTime: Date;
    }>
  ) {
    try {
      const announcement = await this.announcementService.updateAnnouncement(
        id,
        updateData
      );
      return {
        act_id: 93,
        code: 0,
        data: announcement,
        msg: "公告更新成功",
      };
    } catch (error: any) {
      return {
        act_id: 93,
        code: -1,
        msg: error?.message || "更新公告失败",
      };
    }
  }

  /**
   * 删除公告
   * DELETE /announcement/:id
   */
  @Delete(":id")
  @UseGuards(AuthGuard)
  async deleteAnnouncement(@Param("id") id: number) {
    try {
      const result = await this.announcementService.deleteAnnouncement(id);
      return {
        act_id: 94,
        code: 0,
        data: result,
        msg: "公告删除成功",
      };
    } catch (error: any) {
      return {
        act_id: 94,
        code: -1,
        msg: error?.message || "删除公告失败",
      };
    }
  }

  /**
   * 发布公告
   * POST /announcement/:id/publish
   */
  @Post(":id/publish")
  @UseGuards(AuthGuard)
  async publishAnnouncement(@Param("id") id: number) {
    try {
      const result = await this.announcementService.publishAnnouncement(id);
      return {
        act_id: 95,
        code: 0,
        data: result,
        msg: "公告发布成功",
      };
    } catch (error: any) {
      return {
        act_id: 95,
        code: -1,
        msg: error?.message || "发布公告失败",
      };
    }
  }

  /**
   * 下线公告
   * POST /announcement/:id/offline
   */
  @Post(":id/offline")
  @UseGuards(AuthGuard)
  async offlineAnnouncement(@Param("id") id: number) {
    try {
      const result = await this.announcementService.offlineAnnouncement(id);
      return {
        act_id: 96,
        code: 0,
        data: result,
        msg: "公告下线成功",
      };
    } catch (error: any) {
      return {
        act_id: 96,
        code: -1,
        msg: error?.message || "下线公告失败",
      };
    }
  }

  /**
   * 获取重要公告
   * GET /announcement/important?limit=5
   */
  @Get("important")
  async getImportantAnnouncements(@Query("limit") limit?: number) {
    try {
      const announcements = await this.announcementService.getImportantAnnouncements(
        limit || 5
      );
      return {
        act_id: 97,
        code: 0,
        list: announcements,
      };
    } catch (error: any) {
      return {
        act_id: 97,
        code: -1,
        msg: error?.message || "获取重要公告失败",
        list: [],
      };
    }
  }

  /**
   * 搜索公告
   * GET /announcement/search?keyword=关键词&pageNum=0&pageSize=20
   */
  @Get("search")
  async searchAnnouncements(
    @Query("keyword") keyword: string,
    @Query("pageNum") pageNum?: number,
    @Query("pageSize") pageSize?: number
  ) {
    try {
      if (!keyword) {
        return {
          act_id: 98,
          code: -1,
          msg: "搜索关键词不能为空",
          list: [],
        };
      }

      const result = await this.announcementService.searchAnnouncements(
        keyword,
        pageNum || 0,
        pageSize || 20
      );

      return {
        act_id: 98,
        code: 0,
        list: result.list,
        total: result.total,
        pageNum: result.pageNum,
        pageSize: result.pageSize,
        totalPages: result.totalPages,
      };
    } catch (error: any) {
      return {
        act_id: 98,
        code: -1,
        msg: error?.message || "搜索公告失败",
        list: [],
      };
    }
  }

  /**
   * 获取公告统计信息
   * GET /announcement/stats
   */
  @Get("stats")
  @UseGuards(AuthGuard)
  async getAnnouncementStats() {
    try {
      const stats = await this.announcementService.getAnnouncementStats();
      return {
        act_id: 99,
        code: 0,
        data: stats,
      };
    } catch (error: any) {
      return {
        act_id: 99,
        code: -1,
        msg: error?.message || "获取公告统计失败",
      };
    }
  }

  /**
   * 批量操作公告
   * POST /announcement/batch
   */
  @Post("batch")
  @UseGuards(AuthGuard)
  async batchOperation(
    @Body()
    batchData: {
      operation: "publish" | "offline" | "delete";
      ids: number[];
    }
  ) {
    try {
      const { operation, ids } = batchData;
      const results = [];

      for (const id of ids) {
        try {
          let result;
          switch (operation) {
            case "publish":
              result = await this.announcementService.publishAnnouncement(id);
              break;
            case "offline":
              result = await this.announcementService.offlineAnnouncement(id);
              break;
            case "delete":
              result = await this.announcementService.deleteAnnouncement(id);
              break;
            default:
              throw new Error("不支持的操作类型");
          }
          results.push({ id, success: true, result });
        } catch (error: any) {
          results.push({ id, success: false, error: error?.message });
        }
      }

      const successCount = results.filter((r) => r.success).length;
      const failCount = results.filter((r) => !r.success).length;

      return {
        act_id: 100,
        code: 0,
        data: {
          results,
          successCount,
          failCount,
          totalCount: ids.length,
        },
        msg: `批量操作完成，成功 ${successCount} 个，失败 ${failCount} 个`,
      };
    } catch (error: any) {
      return {
        act_id: 100,
        code: -1,
        msg: error?.message || "批量操作失败",
      };
    }
  }
} 